package com.quickcancellation.crm.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.quickcancellation.crm.config.LogAspect;
import com.quickcancellation.crm.pojo.dto.PageParamsDto;
import com.quickcancellation.crm.pojo.dto.ResponseDto;
import com.quickcancellation.crm.pojo.entity.Product;
import com.quickcancellation.crm.pojo.entity.Productitem;
import com.quickcancellation.crm.pojo.entity.Userinfo;
import com.quickcancellation.crm.service.IProductService;
import com.quickcancellation.crm.service.IProductitemService;
import com.quickcancellation.crm.service.IUserinfoService;
import com.quickcancellation.crm.utils.ExcelExporter;
import com.quickcancellation.crm.utils.ResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.MapUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2023-02-04
 */
@RequestMapping("/product")
@CrossOrigin
@RestController
@SaCheckLogin
@Api(tags = "产品管理模块")
@SaCheckRole("product")
public class ProductController {

    private final static Logger logger = LoggerFactory.getLogger(ProductController.class);

    @Autowired
    private IProductService productService;

    @Autowired
    private IUserinfoService userinfoService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Resource
    private IProductitemService productitemService;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @GetMapping(value = "/excel1", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseEntity<byte[]> exportToExcel(HttpServletResponse response) throws IOException {

        List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT productCode,productName,brandId,batchUnit,singleUnit,batchCount,price,productItem,status,remark,createOp,createTime,updateOp,updateTime FROM pd_t_product");
        List<Map<String, Object>> targetList = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            targetList.addAll(list);
        }


        String [] columns = {"产品编码",
                "产品名称",
                "品牌id",
                "分销单位",
                "单品单位",
                "标项系数",
                "默认标箱价",
                "品规",
                "状态",
                "备注",
                "创建人",
                "创建时间",
                "更新人",
                "更新时间"};
        long startTime = System.currentTimeMillis();
        Workbook workbook = ExcelExporter.export2Excel(targetList, columns);

        // 将工作簿转换为字节数组
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        byte[] bytes = outputStream.toByteArray();

        // 设置响应头信息
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "output.xlsx");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentLength(bytes.length);
        long endTime = System.currentTimeMillis();


        logger.info("1---不开线程池26w数据导出到excel时间():{}s",((endTime - startTime)/1000));

        return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
    }

    @GetMapping(value = "/excel2", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseEntity<byte[]> exportToExcel2(HttpServletResponse response) throws Exception {


        List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT productCode,productName,brandId,batchUnit,singleUnit,batchCount,price,productItem,status,remark,createOp,createTime,updateOp,updateTime FROM pd_t_product");

        List<Map<String, Object>> targetList =  new CopyOnWriteArrayList<>();

        for (int i = 0; i < 10; i++) {
            targetList.addAll(list);
        }


        String [] columns = {"产品编码",
                "产品名称",
                "品牌id",
                "分销单位",
                "单品单位",
                "标项系数",
                "默认标箱价",
                "品规",
                "状态",
                "备注",
                "创建人",
                "创建时间",
                "更新人",
                "更新时间"};
        long startTime = System.currentTimeMillis();
        Workbook workbook = ExcelExporter.export2ExcelToThread(targetList, columns);

        // 将工作簿转换为字节数组
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        byte[] bytes = outputStream.toByteArray();

        // 设置响应头信息
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "output.xlsx");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentLength(bytes.length);

        long endTime = System.currentTimeMillis();


        logger.info("2---开线程池26w数据导出到excel时间():{}s",((endTime - startTime)/1000));

        return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
    }


    /**
     * 分页查询列表
     * @param params
     * @return
     */
    @PostMapping("/list")
    @ApiOperation("分页查询列表")
    @LogAspect
//    @SaCheckRole("product")
    public ResponseDto getProductList(@RequestBody PageParamsDto<Product> params) {

        //logger.info("入参是:: " + JSONObject.toJSONString(params));

        IPage<Product> page = productService.selectProductList(params);
//        List<Product> productList = productService.getProductList(params);

        return ResponseUtil.success(page.getTotal(), page.getRecords());
    }

    /**
     * 保存
     * @param params
     * @return
     */
    @LogAspect
    @ApiOperation("保存产品")
    @PostMapping("/save")
    public ResponseDto saveProduct(@RequestBody Product params) {
        //logger.info("入参是:: " + JSONObject.toJSONString(params));

        // 格式化时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date nowDate = new Date();

        String formatDate = format.format(nowDate);

        // 获取用户信息
        Userinfo userInfo = userinfoService.getUserInfoByRequest(httpServletRequest);

        params.setUpdateTime(formatDate);
        params.setCreateOp(userInfo.getUsername());
        params.setUpdateOp(userInfo.getUsername());
        params.setCreateTime(formatDate);

        productService.save(params);

        return ResponseUtil.success();
    }

    /**
     * 根据id删除
     * @param params
     * @return
     */
    @LogAspect
    @ApiOperation("删除产品")
    @PostMapping("/delete")
    public ResponseDto delete(@RequestBody Map params) {
        //logger.info("入参是:: " + JSONObject.toJSONString(params));

        boolean result = productService.removeById(MapUtils.getInteger(params, "id"));

        return result ? ResponseUtil.success():ResponseUtil.fail("501","删除失败");


    }

    /**
     * 根据id更新
     * @param product
     * @return
     */
    @LogAspect
    @ApiOperation("更新产品-根据id(id必传)")
    @PostMapping("/update")
    public ResponseDto updateProduct(@RequestBody Product product) {
        //logger.info("入参是:: " + JSONObject.toJSONString(product));

        boolean result = productService.updateById(product);

        return result ? ResponseUtil.success():ResponseUtil.fail("501","更新失败");

    }

    @LogAspect
    @ApiOperation("获取品规列表")
    @PostMapping("/getProductItem3List")
    public ResponseDto getProductItem3List(@RequestBody Product product) {
        QueryWrapper<Productitem> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("itemType",3);

        List<Productitem> list = productitemService.list(queryWrapper);

        return ResponseUtil.success(list);
    }
}
